<?php
if(isset($_POST['backDown']))
{
	header("Access-Control-Allow-Origin: *");
	header("Access-Control-Allow-Credentials: true");
	if(!isset($_POST['type']))exit('server');

	$dir = '../';
	if($_POST['type'] === 'json')
	{
		$data = put_json($_POST['data']);
		$dir .= 'JSON';
	}
	else
	{
		$data = base64_decode($_POST['data']);
		$dir .= 'IMAGE/'.$_POST['time'];
	}
	
	copy_file($data,"$dir/".$_POST['filename'],'make');
	exit($dir);
}
$host = 'localhost';
$browser = 'Safari';
if($_SERVER['HTTP_HOST'] !== $host || !strpos($_SERVER['HTTP_USER_AGENT'], $browser))
{
	echo "<h1 style='word-wrap: break-word;text-indent: 2em;'>在【phpwin】界面点击左上角【三】横杠，点击【Settings】进入设置页面：</h1>";
	if($_SERVER['HTTP_HOST'] !== $host)echo "<h2 style='word-wrap: break-word;text-indent: 2em;'>在【Default host】一栏将【127.0.0.1】改为【localhost】</h2>";
	if(!strpos($_SERVER['HTTP_USER_AGENT'], $browser))echo "<h2 style='word-wrap: break-word;text-indent: 2em;'>将【Use in-App Safari】选项改为开启状态</h2>";
}
ini_set("memory_limit",-1);
ini_set('precision', -1);
ini_set('serialize_precision', -1);
set_time_limit(0);

$ZipList = get_json('ZipList.txt');
$zip = new ZipArchive;
foreach(scandir('./') as $v)
{
	if(in_array($v,array('.', '..'))){continue;}
	if(in_array(pathinfo($v, PATHINFO_EXTENSION),array('zip', 'apk')))
	{
		$file = str_replace('离线版','LXB',$v);
		$file = str_replace('碧蓝档案','BLDA',$file);
		$file = str_replace('尘白禁区','CBJQ',$file);
		$file = str_replace('千年之旅','QNZL',$file);
		$file = str_replace('客户端（需联网）','KHD',$file);
		if($v !== $file)rename($v,$file);
		$v = $file;
		$dir = strval(pathinfo($v, PATHINFO_FILENAME));
		$res = $zip->open($v);
		if($res === TRUE)
		{
			if(!is_dir($dir))unset($ZipList[$dir]);
			if(!isset($ZipList[$dir]))
			{
				$zip->extractTo($dir);
				$ZipList[$dir] = $dir;
			}
			$zip->close();
		}
	}
}
$MTList = [];
foreach($ZipList as $k=>$v)
{
	$k = strval($k);
	if($k === $v)
	{
		$html = SearchFile($k);
		if(isset($html[0]))
		{
			$v = $html[0];
			$ZipList[$k] = $v;
		}
	}
	if($k !== $v)
	{
		if(file_exists($v))$MTList[] = $ZipList[$k];
		else unset($ZipList[$k]);
	}
}
copy_file(put_json($ZipList),'ZipList.txt','make');
if(count($MTList) < 1)
{
	echo '<h1>请将MoeTalk的【zip】压缩包或【apk】文件放入<span style="color:red;">【文件/我的iPhone/phpwin/root】</span>文件夹内并重启此页面！</h1>';
	echo '<h2><a href="https://gitlab.com/ggg555ttt/MoeTalk/-/archive/main/MoeTalk-main.zip">最新版压缩包下载地址</a></h2>';
	echo '<h2>下载的文件应该可以在<span style="color:red;">【文件/我的iPhone/下载】</span>中找到</h2>';
	echo '<h2><a href="https://pan.baidu.com/s/1Cc-Us0FM_ehP9h5SDWhrVg?pwd=blda">百度网盘，提取码：blda</a></h2>';
	exit;
}
if($_SERVER['HTTP_HOST'] !== $host || !strpos($_SERVER['HTTP_USER_AGENT'], $browser))exit;

if(count($MTList) < 2)
{
	header("Location: $MTList[0]");
	exit;
}
else
{
	echo "<h1 style='word-wrap: break-word;text-indent: 2em;'>检测到多个MoeTalk，请选择：</h1>";
	foreach($MTList as $v)
	{
		echo "<h2 style='word-wrap: break-word;text-indent: 2em;'><a href='$v'>$v</a></h2>";
	}
}
function mkdirs($dir, $mode = 0777)
{
	if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
	if (!mkdirs(dirname($dir), $mode)) return FALSE;
	return @mkdir($dir, $mode);
}
function copy_file($oldfile,$newfile,$mode = 'copy')
{//复制或生成文件
	mkdirs(dirname($newfile));
	if($mode === 'copy' && file_exists($oldfile))copy($oldfile,"$dir/$file");
	if($mode === 'make')file_put_contents($newfile,$oldfile);//生成文件
}
function SearchFile($pathName,$result=array())
{
	//$pathName = str_replace('\\','/',$pathName);
	//判断传入的变量是否是目录
	if(!is_dir($pathName) || !is_readable($pathName))
	{
		echo "目录 $pathName 不存在！<br>\n";
		return [];
	}
	//读取目录信息
	$allFiles = scandir($pathName);
	//asort($allFiles, SORT_STRING | SORT_FLAG_CASE | SORT_NATURAL); // 对值排序
	//遍历他们
	foreach($allFiles as $fileName)
	{
		//判断是否是.和..因为这两个东西神马也不是。。。
		if(in_array($fileName,array('.', '..'))){continue;}
		//路径加文件名
		$fullName = $pathName.'/'.$fileName;
		//如果是目录的话就继续遍历这个目录
		if(is_dir($fullName) && $fileName !== 'player')
		{
			$result = SearchFile($fullName,$result);//将这个目录中的文件信息存入到数组中
		}
		else
		{
			if($fileName === 'index.html')$result[] = $fullName;
			
		}
	}
	return $result;
}
function get_json($filename)
{
	if(!file_exists($filename))
	{
		copy_file('[]',$filename,'make');
		return [];
	}
	$json = preg_replace('/\/\*.*\*\//Us','',file_get_contents($filename));
	return json_decode($json,true);
}
function put_json($jsonarr,$i = 3)
{
	if($i === 1)return json_encode($jsonarr,JSON_UNESCAPED_UNICODE);//不转汉字
	if($i === 2)return json_encode($jsonarr,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);//不转反斜杠
	if($i === 3)return json_encode($jsonarr,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);//JSON格式化
}